<?php

namespace app\api\controller\merchant;

use Alipay\EasySDK\Kernel\Factory as alipayFactory;
use app\admin\model\UserMoneyLog;
use app\api\model\Car;
use app\api\model\Coupon;
use app\api\model\FaceCate;
use app\api\model\Insure;
use app\api\model\Merchant;
use app\api\model\MerchantArea;
use app\api\model\MerchantCarInsure;
use app\api\model\MerchantCarPrice;
use app\api\model\MerchantCarTime;
use app\api\model\Notice;
use app\api\model\OrderChange;
use app\api\model\OrderContinue;
use app\api\model\OrderFace;
use app\api\model\OrderRefund;
use app\api\model\PhoneCode;
use app\api\model\RefundType;
use app\api\model\User;
use app\api\model\UserCoupon;
use app\api\model\UserIncome;
use app\common\controller\Api;
use app\api\model\BalanceLog;
use app\common\model\CarCate;
use app\common\model\Cash;
use app\common\model\Merchant as MerchatModel;
use app\api\model\MerchantCar;
use app\api\model\Order;
use app\common\model\PlatformLog;
use app\common\model\User as UserModel;
use EasyWeChat\Factory;
use fast\Random;
use think\facade\Config;
use think\facade\Db;
use think\Model;

/**
 * 首页接口.
 */
class Index extends Api
{
    protected $noNeedLogin = ['login','sendCode'];
    protected $noNeedRight = ['*'];
    protected $week_list = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];


    /**
     * 登录
     */
    public function login(){
        $params = $this->request->post();
        $account = $params['account'] ?? '';
        $password = $params['password'] ?? '';
        $code = $params['code'] ?? '';
        $type = $params['type'] ?? 1;
        if(!$type || !in_array($type, [1,2])){
            $this->error('参数错误');
        }
        if ($type == 1 && (!$account || !$password)){
            $this->error('参数错误');
        }
        if ($type == 2 && (!$account || !$code)){
            $this->error('参数错误');
        }
        $userInfo = MerchatModel::where(['merchant_phone' => $account, 'is_delete' => 1, 'examine_status' => 2])->find();

        if (!$userInfo){
            $this->error('账号未找到');
        }
        if($userInfo['status'] == 2){
            $this->error('账号已禁用');
        }
        if($type == 1){
            $newPassword = MerchatModel::saltPassword($password,$userInfo['salt']);
            if ($newPassword != $userInfo['merchant_password']){
                $this->error('密码不正确');
            }
        }else{
            $phone_code = PhoneCode::where('phone', $account)->find();
            if(!$phone_code){
                $this->error('请发送验证码');
            }
            if($phone_code['createtime'] + 5*60 < time()){
                $this->error('验证码已过期');
            }
            if($code != $phone_code['code']){
                $this->error('验证码错误');
            }
            PhoneCode::where('phone', $account)->delete();
        }

        $this->auth->direct($userInfo['id']);
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
    }

    /**
     * 发送验证码
     */
    public function sendCode(){
        $params = $this->request->post();
        $phone = $params['phone'] ?? '';
        $pattern = '/^1[3456789]\d{9}$/';
        if (!$phone || !preg_match($pattern, $phone)) {
            $this->error('手机号错误');
        }
        $phone_code = PhoneCode::where('phone', $phone)->order('createtime', 'desc')->find();
        if($phone_code && $phone_code['createtime'] + 60 > time()){
            $this->error('请求频繁');
        }
        //发送验证码接口
        $code = Random::numeric(6);
        $res = sendMsg($phone, ['code' => $code], 'SMS_464066255');
        Db::name('log')->insert(['content' => json_encode($res, JSON_UNESCAPED_UNICODE)]);
        if(!$res){
            $this->error('发送失败');
        }
        if(isset($res['Code']) && $res['Code'] != 'OK'){
            $this->error('发送失败');
        }
        if(!$phone_code){
            $res = \app\admin\model\PhoneCode::insert(['phone' => $phone, 'code' => $code, 'createtime' => time()]);
        }else{
            $res = \app\admin\model\PhoneCode::where('id', $phone_code['id'])->update(['code' => $code, 'createtime' => time()]);
        }
        if($res){
            $this->success('发送成功');
        }else{
            $this->error('发送失败');
        }
    }

    /**
     * 首页数据
     */
    public function indexup()
    {
        $user = $this->auth->getUser();
        //店铺信息
        $shopData = [
            'logo' => $user['shop_logo'],
            'name' => $user['shop_name'],
            'balance' => floatval($user['shop_balance']),
            'signing_time' => $user['signing_time'] ? date('Y-m-d', $user['signing_time']) : '',
            'status' => $user['status']
        ];
        //收入统计信息
        $incomeInfo = Merchant::income($user['id']);
        //公告信息
        $notice = Notice::noticeInfo($user);
        //车辆信息
        $carInfo = MerchantCar::carinfo($user['id']);
        //订单信息
        $orderInfo = Order::orderInfo($user['id']);
        $newData = [
            'shop' => $shopData,
            'incom' => $incomeInfo,
            'notice' => $notice,
            'car' => $carInfo,
            'order' => $orderInfo
        ];
        $this->success('请求成功',$newData);
    }

    /**
     * 收益列表
     */
    public function incomeList()
    {
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $type = $requestData['type']??0;
        $start_time = $requestData['start_time']??'';
        $end_time = $requestData['end_time']??'';
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??0;
        if(!$type || !in_array($type, [1,2])){
            $this->error('请求类型错误');
        }
        $where = ['merchant_id' => $user['id'],'type' => 1];
        //收益
        if($type == 1){
            $builder = BalanceLog::with('order')->field('order_id,amount,type,createtime')->where($where)->whereMonth('createtime');
            $list = $builder->order('createtime', 'desc')->page($page, $limit)->select()->toArray();
            $order_money = BalanceLog::where($where)->whereMonth('createtime')->sum('amount');
            $order_num = BalanceLog::where($where)->whereMonth('createtime')->count();
        }else{
            $builder = BalanceLog::with('order')->field('order_id,amount,type,createtime')->where($where)->whereYear('createtime');
            if($start_time && $end_time){
                $start_time = date('Y-m-1', strtotime($start_time));
                $end_time = date('Y-m-t 23:59:59', strtotime($end_time));
                $builder->whereBetweenTime('createtime', $start_time, $end_time);
            }
            $list = $builder->order('createtime', 'desc')->page($page, $limit)->select()->toArray();
            $order_money = BalanceLog::where($where)->whereYear('createtime')->sum('amount');
            $order_num = BalanceLog::where(['merchant_id' => $user['id'],'type' => 1])->whereYear('createtime')->count();
        }

        foreach ($list as $key=>$value){
            $list[$key]['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
            $list[$key]['amount'] = floatval($value['amount']);
        }
        $newData = [
            'order_num' => $order_num,
            'order_money' => $order_money,
            'list' => $list
        ];
        $this->success('请求成功',$newData);
    }

    /**
     * 公告列表
     */
    public function noticeList()
    {
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $model = new Notice();
        $data = $model->noticeList($requestData, $user);
        $this->success('请求成功',$data);
    }

    /**
     * 公告详情
     */
    public function noticeDetails()
    {
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $model = new Notice();
        $data = $model->noticeDetails($requestData, $user);
        $this->getReturnData($data);
    }

    /**
     * 优惠券活动列表
     */
    public function couponList()
    {
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $model = new Coupon();
        $data = $model->couponList($requestData, $user);
        $this->getReturnData($data);
    }

    /**
     * 优惠券报名
     */
    public function couponJoin()
    {
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $model = new Coupon();
        $data = $model->couponJoin($requestData, $user);
        $this->getReturnData($data);
    }

    /**
     * 订单列表
     */
    public function orderList(){
        $requestData = $this->request->post();
        $status = $requestData['status']??0;
        $search = $requestData['search']??'';
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??0;
        $user = $this->auth->getUser();
        $where = [['is_delete', '=', 1], ['merchant_id', '=', $user['id']]];
        if(!in_array($status, [0,1,2,3,4])){
            $this->error('请求类型错误');
        }
        if(!$status){
            $where[] = ['status', 'in', '1,2,3,4'];
        }else{
            $where[] = ['status', '=', $status];
        }
        if($search){
            $where[] = ['out_trade_no|car_number', 'like', '%'.$search.'%'];
        }
        $list = Order::with(['order_change_pay', 'order_change_unpay', 'order_continue_pay', 'order_continue_unpay', 'order_face_pay', 'order_face_unpay'])->field('id,out_trade_no,merchant_id,merchant_car_id,start_time,end_time,days,all_money,status,send_type,deposit_type,car_name,car_number,merchant_car_name,shop_name,shop_logo,shop_address,change_status,continue_status,face_status,pick_address,return_address,driver_id,user_phone,driver_name,driver_number,shop_service')->where($where)->order('createtime','desc')->page($page, $limit)->select()->toArray();
        if($list){
            foreach ($list as $key=>$value){
                $value['status_text'] = Order::fetchStatus($value['status']);
                $value['shop_service'] = Merchant::services($value['shop_service']);
                $all_money = $value['all_money'];
                if($value['order_change_pay']){
                    $change_money_list = array_column($value['order_change_pay'], 'diff_money');
                    $change_money = array_sum($change_money_list);
                    $all_money = bcadd($all_money, $change_money, 2);
                    $change_car_ids = [];
                    $change_car_prices = [];
                    foreach ($value['order_change_pay'] as $ks=>$vs){
                        if($vs['merchant_car_id']){
                            $change_car_ids[] = $vs['merchant_car_id'];
                        }
                        if($vs['price']){
                            $change_car_prices[] = $vs['price'];
                        }
                    }
                    if($change_car_ids){
                        $value['merchant_car_id'] = $change_car_ids[0];
                        $new_merchant_car = MerchantCar::field('car_id,merchant_car_name,car_price')->with('cars')->where('id', $value['merchant_car_id'])->find();
                        $value['car_name'] = $new_merchant_car['car_name'];
                        $value['car_image'] = $new_merchant_car['car_image'];
                        $value['merchant_car_name'] = $new_merchant_car['merchant_car_name'];
                    }
                    if($change_car_prices){
                        $value['price'] = $change_car_prices[0];
                    }
                    if($value['order_change_pay'][0]['other_number']){
                        $value['car_number'] = $value['order_change_pay'][0]['other_number'];
                    }else{
                        $value['car_number'] = MerchantCar::where('id', $value['order_change_pay'][0]['merchant_car_id'])->value('car_number');
                    }
                }
                if($value['order_continue_pay']){
                    $continue_money_list = array_column($value['order_continue_pay'], 'all_money');
                    $continue_money = array_sum($continue_money_list);
                    $all_money = bcadd($all_money, $continue_money, 2);

                    $value['end_time'] = $value['order_continue_pay'][0]['end_time'];
                }
                if($value['order_face_pay']){
                    $face_money_list = array_column($value['order_face_pay'], 'all_money');
                    $face_money = array_sum($face_money_list);
                    $all_money = bcadd($all_money, $face_money, 2);
                }
                $value['all_money'] = $all_money;
                $value['order_change_id'] = $value['order_change_unpay']['id']??'';
                $value['order_continue_id'] = $value['order_continue_unpay']['id']??'';
                $value['order_face_id'] = $value['order_face_unpay']['id']??'';
                $res = getDhir($value['start_time'], $value['end_time']);
                $start_time = [
                    'day' => date('m月d日', $value['start_time']),
                    'time' => date('H:i', $value['start_time']),
                    'week' => $this->week_list[date('w', $value['start_time'])]
                ];
                $value['start_time_list'] = $start_time;
                $end_time = [
                    'day' => date('m月d日', $value['end_time']),
                    'time' => date('H:i', $value['end_time']),
                    'week' => $this->week_list[date('w', $value['end_time'])]
                ];
                if($res['d'] > 0){
                    $days_new = $res['h'] > 0 ? $res['d'] . '天' . $res['h'] . '小时' : $res['d'] . '天';
                }else{
                    $days_new = $res['h'] . '小时';
                }

                $value['days_new'] = $days_new;
                $value['end_time_list'] = $end_time;
                unset($value['order_change_pay'],$value['order_change_unpay'],$value['order_continue_pay'],$value['order_continue_unpay'],$value['order_face_pay'],$value['order_face_unpay']);
                $list[$key] = $value;
            }
        }
        $this->success('操作成功', $list);
    }

    /**
     * 订单详情
     */
    public function orderDetail(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $id = $requestData['id']??0;
        $where = ['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id];
        $order = Order::with(['order_continue', 'order_face', 'order_change_pay'])->field('id,out_trade_no,
        merchant_id,merchant_car_id,start_time,end_time,days,price,rental_money,deposit,
        all_money,status,deposit_status,send_type,car_name,merchant_car_name,car_number,
        car_image,car_label,car_note,shop_name,shop_logo,shop_address,shop_service,shop_phone,
        driver_name,driver_number,coupon_id,coupon_money,createtime,user_phone,shop_point,insurance,
        insurance_id,insurance_price,pay_type,deposit_type,driver_idcard_face,driver_idcard_back,
        driver_license_face,driver_license_back,start_dashboard,end_dashboard,start_check_video,
        end_check_video,start_check_images,end_check_images,start_note,pick_time,end_note,return_time,
        rental_contract,real_return_time,offline_money,offline_note,liquidated_damages,handle_fee,change_status,
        continue_status,face_status,pick_point,pick_address,return_point,return_address,refund_money,refund_time,
        all_change_refund_money,refund_status,cancel_time,cancel_reason,cancel_type,end_confirm,pick_fee,return_fee,
        night_pick_fee,night_return_fee,order_refund_status,order_refund_type,order_refund_money,order_refund_note,
        order_refund_addtime,distance,total_distance_price,distance_price')->where($where)->find();
        if(!$id || !$order){
            $this->error('订单不存在');
        }
        $order = $order->toArray();
        //如果有换车订单 租赁费用 保险费用 手续费 总价 重新计算显示
        $all_money = $order['all_money'];
        if($order['order_change_pay']){
            $change_money_list = array_column($order['order_change_pay'], 'diff_money');
            $change_money = array_sum($change_money_list);
            $all_money = bcadd($all_money, $change_money, 2);
            $order['all_money'] = $all_money;
            $change_car_ids = [];
            $change_car_prices = [];
            $change_car_rentals = [];
            $change_car_deposits = [];
            $change_car_handles = [];
            foreach ($order['order_change_pay'] as $ks=>$vs){
                if($vs['merchant_car_id']){
                    $change_car_ids[] = $vs['merchant_car_id'];
                }
                if($vs['price'] > 0){
                    $change_car_prices[] = $vs['price'];
                }
                if($vs['rental_money'] > 0){
                    $change_car_rentals[] = $vs['rental_money'];
                }
                if($vs['deposit'] > 0){
                    $change_car_deposits[] = $vs['deposit'];
                }
                if($vs['handle_fee'] > 0){
                    $change_car_handles[] = $vs['handle_fee'];
                }
            }
            if($change_car_ids){
                $order['merchant_car_id'] = $change_car_ids[0];
                $new_merchant_car = MerchantCar::field('car_id,merchant_car_name,car_price,drive,displacement')->with('carss')->where('id', $order['merchant_car_id'])->find();
                $order['car_name'] = $new_merchant_car['car_name'];
                $order['car_image'] = $new_merchant_car['car_image'];
                $order['merchant_car_name'] = $new_merchant_car['merchant_car_name'];
                $car_gear = $new_merchant_car['car_gear'] == 1 ? '手动' : '自动';
                $order['car_label'] = $new_merchant_car['car_site'].'座|'.$new_merchant_car['car_gate'].'门|'.$car_gear.'|'.$new_merchant_car['displacement'];
            }
            if($change_car_prices){
                $order['price'] = $change_car_prices[0];
            }
            if($change_car_rentals){
                $order['rental_money'] = $change_car_rentals[0];
            }
            if($change_car_deposits){
                $order['deposit'] = $change_car_deposits[0];
            }
            if($change_car_handles){
                $order['handle_fee'] = $change_car_handles[0];
            }
            if($order['order_change_pay'][0]['other_number']){
                $order['car_number'] = $order['order_change_pay'][0]['other_number'];
            }else{
                $order['car_number'] = MerchantCar::where('id', $order['order_change_pay'][0]['merchant_car_id'])->value('car_number');
            }
        }
        if($order['order_face']){
            foreach ($order['order_face'] as $kc=>$vc){
                $order['order_face'][$kc]['all_money'] = floatval($vc);
                $order['order_face'][$kc]['time_end'] = $vc['time_end'] ? date('Y-m-d H:i:s', $vc['time_end']) : '';
                $order['order_face'][$kc]['type'] = FaceCate::where(['is_delete' => 1, 'id' => $vc['type']])->value('name');
            }
        }
        if($order['order_continue']){
            foreach ($order['order_continue'] as $kn => $vn){
                $order['order_continue'][$kn]['all_money'] = floatval($vn['all_money']);
            }
        }
        $order['status_text'] = Order::fetchStatus($order['status']);
        $order['change_status_text'] = Order::fetchChangeStatus($order['change_status']);
        $order['continue_status_text'] = Order::fetchContinueStatus($order['continue_status']);
        $order['face_status_text'] = Order::fetchFaceStatus($order['face_status']);
        $res = getDhir($order['start_time'], $order['end_time']);
        if($res['d'] > 0){
            $days_new = $res['h'] > 0 ? $res['d'] . '天' . $res['h'] . '小时' : $res['d'] . '天';
        }else{
            $days_new = $res['h'] . '小时';
        }
        $order['rental_money'] = floatval($order['rental_money']);
        $order['all_money'] = floatval($order['all_money']);
        $order['coupon_money'] = floatval($order['coupon_money']);
        $order['insurance'] = floatval($order['insurance']);
        $order['offline_money'] = floatval($order['offline_money']);
        $order['liquidated_damages'] = floatval($order['liquidated_damages']);
        $order['refund_money'] = floatval($order['refund_money']);
        $order['price'] = floatval($order['price']);
        $order['night_pick_fee'] = floatval($order['night_pick_fee']);
        $order['night_return_fee'] = floatval($order['night_return_fee']);
        $order['all_change_refund_money'] = floatval($order['all_change_refund_money']);
        $order['days_new'] = $days_new;
        $order['start_time'] = date('m月d日 H:i', $order['start_time']);
        $order['end_time'] = date('m月d日 H:i', $order['end_time']);
        $order['send_type_text'] = Order::fetchSendType($order['send_type']);
        $order['shop_service_list'] = explode(',', $order['shop_service']);
        $order['deposit_status_text'] = Order::fetchDepositStatus($order['deposit_status']);
        $order['createtime_text'] = date('Y-m-d H:i:s', $order['createtime']);
        $shop_point = explode(',', $order['shop_point']);
        $order['longitude'] = (float)$shop_point[0];
        $order['latitude'] = (float)$shop_point[1];
        $service_phone = \app\api\model\Config::configFind(['name' => 'service_phone']);
        $order['service_phone'] = $service_phone;
        $order['start_check_images'] = explode(',', $order['start_check_images']);
        $order['end_check_images'] = explode(',', $order['end_check_images']);
        $order['pick_time'] = $order['pick_time'] ? date('Y-m-d H:i:s', $order['pick_time']) : '';
        $order['return_time'] = $order['return_time'] ? date('Y-m-d H:i:s', $order['return_time']) : '';
        $order['refund_time'] = $order['refund_time'] ? date('Y-m-d H:i:s', $order['refund_time']) : '';
        $order['order_refund_addtime'] = $order['order_refund_addtime'] ? date('Y-m-d H:i:s', $order['order_refund_addtime']) : '';
        $config = \app\api\model\Config::where('name', 'in','car_guarantee,cancel_time1,cancel_money1,cancel_money2,notice')->column('value', 'name');
        $order['cancel_time1'] = $config['cancel_time1'];
        $order['cancel_money1'] = $config['cancel_money1'];
        $order['cancel_money2'] = $config['cancel_money2'];
        $order['notice'] = $config['notice'];
        $order['car_guarantee'] = $config['car_guarantee'];
        $order['rental_contract'] = $order['rental_contract'] ? explode(',', $order['rental_contract']) : [];
        $order['order_refund_type'] = RefundType::where('id', $order['order_refund_type'])->value('name');
        //租车保障
        $insure = MerchantCarInsure::field('id,insure_id,price')->with('insures')->where(['is_delete' => 1])->where('insure_id', $order['insurance_id'])->find();
        if($insure){
            $insure['price'] = floatval($insure['price']);
        }
        $order['insure'] = $insure;
        $order['traffic_notice'] = Merchant::where('id', $order['merchant_id'])->value('traffic_notice');
        $this->success('请求成功', $order);
    }

    /**
     * 排车(换车)
     */
    public function orderChangeAdd(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $id = $requestData['id']??0;
        $type = $requestData['type']??0;
        $request_type = $requestData['request_type']??0;
        $merchant_car_id = $requestData['merchant_car_id']??0;
        $other_number = $requestData['other_number']??'';
        if(!$id || !$request_type || !in_array($request_type, [1,2])){
            $this->error('参数错误');
        }
        $where = ['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id];
        $order = Order::field('id,out_trade_no,user_id,merchant_car_id,merchant_id,start_time,end_time,days,price,rental_money,deposit,handle_fee,all_money,status,deposit_status,send_type,car_image,merchant_car_name,car_number,car_name,car_label,createtime,insurance_id,insurance,insurance_price,pay_type,deposit_type,change_status,continue_status,face_status,pick_point,return_point,pick_fee,return_fee,night_pick_fee,night_return_fee,coupon_id,coupon_money')->where($where)->find();
        if(!$order){
            $this->error('订单不存在');
        }
        $order = $order->toArray();
        if($order['status'] != 1){
            $text = Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        $change_model = new OrderChange();
        //订单换车订单
        $order_change = $change_model->where(['is_delete' => 1, 'order_id' => $order['id'], 'pay_status' => 1])->count();
        if($order_change){
            $this->error('该订单已有待支付的换车订单');
        }
        if($request_type == 2 && $type == 1 && $other_number){
            $this->error('外部车辆只能免费还车');
        }
        if($request_type == 2 && $type == 2 && ((!$merchant_car_id && !$other_number) || ($merchant_car_id && $other_number))){
            $this->error('参数错误');
        }
        $rental_money = 0;
        $diff_money = 0;
        $all_money = 0;
        $car_deposit = 0;
        $pick_fee = 0;
        $return_fee = 0;
        $coupon_money = 0;
        if($merchant_car_id){
            $merchant_car = MerchantCar::with('carss')->where(['is_delete' => 1, 'id' => $merchant_car_id])->find();
            if(!$merchant_car){
                $this->error('商家车辆不存在');
            }
            if($merchant_car['status'] == 2){
                $this->error('商家车辆已下架');
            }
            //临时下架时间
            $last_time = strtotime("-1 month");
            $merchant_car_time = MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('end_time', '>', $last_time)->select();
            foreach ($merchant_car_time as $ke=>$vl){
                $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], $order['start_time'], $order['end_time']);
                if($is_time_cross){
                    $this->error('租赁时间段内商家车辆会临时下架');
                }
            }

            $stay_area = false;
            //判断区域 确定取车还车价格
            $merchant_area = MerchantArea::field('id,price,area,stay_time')->where(['is_delete' => 1, 'status' => 1, 'merchant_id' => $order['merchant_id']])->select()->toArray();
            $point = explode(',', $order['pick_point']);
            foreach ($merchant_area as $kee => $vll){
                //判断是否在区域内
                $area = getNewArea($vll['area']);
                $is_area = is_ptin_poly($point[0], $point[1], $area);
                if($is_area){
//                    if($order['start_time'] - time() < $vll['stay_time']){
//                        $this->error('改区域商家提前等待时间最少为'.$vll['stay_time'].'分钟');
//                    }
                    $pick_fee = $vll['price'];
                    $return_fee = $vll['price'];
                    $stay_area = true;
                }
            }

//            if(!$stay_area){
//                if($order['start_time'] - time() < $user['stay_time']*60){
//                    $this->error('商家提前等待时间最少为'.$user['stay_time'].'分钟');
//                }
//            }

            //商家车辆远期价格
            $date_list = createDateRange(date('Y-m-d', $order['start_time']), date('Y-m-d', $order['end_time']));
            $merchant_car_price_list = MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $merchant_car_id])->where('end_time', '>', time())->select()->toArray();
            $new_date_list = [];
            foreach ($date_list as $kk=>$vv){
                $new_date['date'] = $vv;
                $new_date['price'] = $merchant_car['car_price'];
                foreach ($merchant_car_price_list as $kkk=>$vvv){
                    if(strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']){
                        if($order['days'] < $vvv['days']){
                            return ['status' => 0, 'message' => '起租天数必须大于' . $vvv['days'] , 'result' => ''];
                        }
                        $new_date['price'] = $vvv['price'];
                    }
                }
                $new_date_list[] = $new_date;
            }

            $price_list = array_column($new_date_list, 'price');
            $prices = implode(',', $price_list);
            //租车费用
            $rental_money = array_sum($price_list);
            //平均单价
            $car_price = bcdiv($rental_money, count($price_list), 2);
            if($rental_money < 0.01){
                $this->error('租车费用必须大于0.01');
            }

            $car_deposit = $merchant_car['car_deposit']??0;
        }

        if($request_type == 2 && $type == 2 && $order['coupon_id']){
            $coupon_money = $order['coupon_money'];
            if($coupon_money < $rental_money){
                $this->error('租赁金额未达到之前的优惠金额');
            }
        }
        $all_money = bcadd($rental_money-$coupon_money, ($pick_fee+$return_fee), 2);
        //查询最后一个有偿换车订单
        $last_pay_order = OrderChange::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order['id'], 'type' => 2])->where('pay_status', 'in', '2')->order('createtime', 'desc')->find();
        if(!$last_pay_order){
            $diff_money = $type == 1 ? 0 : bcsub($all_money, $order['all_money'], 2);
        }else{
            $diff_money = $type == 1 ? 0 : bcsub($all_money, $last_pay_order['all_money'], 2);
            $order['price'] = $last_pay_order['price'];
        }
        //最后一个有车辆的换车订单
        $last_merchant_order = OrderChange::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order['id']])->where('pay_status', 'in', '2')->where('merchant_car_id', '>', 0)->order('createtime', 'desc')->find();
        if($last_merchant_order){
            $last_merchant_car = MerchantCar::field('car_id,merchant_car_name,car_price,drive,displacement')->with('carss')->where('id', $last_merchant_order['merchant_car_id'])->find();
            $order['car_name'] = $last_merchant_car['car_name'];
            $order['car_image'] = $last_merchant_car['car_image'];
            $order['merchant_car_name'] = $last_merchant_car['merchant_car_name'];
            $car_gear = $last_merchant_car['car_gear'] == 1 ? '手动' : '自动';
            $order['car_label'] = $last_merchant_car['car_site'].'座|'.$last_merchant_car['car_gate'].'门|'.$car_gear.'|'.$last_merchant_car['displacement'];
        }
        //最后一个换车订单
        $last_change_order = OrderChange::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order['id']])->where('pay_status', 'in', '2')->order('createtime', 'desc')->find();
        if($last_change_order){
            if($last_change_order['merchant_car_id'] > 0){
                $last_car_number = MerchantCar::where('id', $last_change_order['merchant_car_id'])->value('car_number');
            }else{
                $last_car_number = $last_change_order['other_number'];
            }
            $order['car_number'] = $last_car_number;
        }
        if($request_type == 1){//查看
            $new_merchant_car = [];
            if($merchant_car_id){
                $car_gear = $merchant_car['car_gear'] == 1 ? '手动' : '自动';
                $labels = $merchant_car['car_site'] . '座|' . $merchant_car['car_gate'] . '门|' . $car_gear . '|' . $merchant_car['displacement'];
                $new_merchant_car = [
                    'id' => $merchant_car_id,
                    'car_name' => $merchant_car['car_name'],
                    'car_image' => $merchant_car['car_image'],
                    'merchant_car_name' => $merchant_car['merchant_car_name'],
                    'car_number' => $merchant_car['car_number'],
                    'car_price' => floatval($merchant_car['car_price']),
                    'car_label' => $labels
                ];
            }
            $order['diff_money'] = floatval($diff_money);
            $order['new_merchant_car'] = $new_merchant_car;
            $order['price'] = floatval($order['price']);
            $order['rental_money'] = floatval($order['rental_money']);
            $order['deposit'] = floatval($order['deposit']);
            $order['handle_fee'] = floatval($order['handle_fee']);
            $order['all_money'] = floatval($order['all_money']);
            $order['insurance'] = floatval($order['insurance']);
            $order['insurance_price'] = floatval($order['insurance_price']);
            $order['pick_fee'] = floatval($order['pick_fee']);
            $order['return_fee'] = floatval($order['return_fee']);
            $order['night_pick_fee'] = floatval($order['night_pick_fee']);
            $order['night_return_fee'] = floatval($order['night_return_fee']);
            $order['coupon_money'] = floatval($order['coupon_money']);
            $order['diff_money'] = floatval($order['diff_money']);
            $this->success('请求成功', $order);
        }else{//提交
            Db::startTrans();
            try {
                if($type == 1){
                    $pay_status = 2;
                    $change_status = 3;
                }else{
                    if($diff_money > 0){
                        $pay_status = 1;
                        $change_status = 2;
                    }else{
                        $pay_status = 2;
                        $change_status = 3;
                    }
                }
                $requestData['user_id']  = $order['user_id'];
                $requestData['order_id']  = $order['id'];
                $requestData['out_trade_no']  = OrderChange::getOutRefundNo();
                $requestData['merchant_id']  = $order['merchant_id'];
                $requestData['merchant_car_id']  = $merchant_car_id ? $merchant_car_id : 0;
                $requestData['price']  = $type == 2 ? $car_price : 0;
                $requestData['rental_money']  = $type == 2 ? $rental_money : 0;
                $requestData['deposit']  = $type == 2 ? $car_deposit : 0;
                $requestData['deposit_status']  = ($type == 2 && $car_deposit > 0) ? 1 : 0;
                $requestData['all_money']  = $type == 2 ? $all_money : 0;
                $requestData['diff_money']  = $type == 2 ? $diff_money : 0;
                $requestData['pay_type']  = $order['pay_type'];
                $requestData['createtime']  = time();
                $requestData['old_merchant_car_id']  = $order['merchant_car_id'];
                $requestData['old_price']  = $order['price'];
                $requestData['pay_status'] = $pay_status;
                $requestData['last_all_money'] = ($type == 2 && $diff_money > 0) ? $diff_money : 0;
                $requestData['pick_fee'] = $type == 2 ? $pick_fee : 0;
                $requestData['return_fee'] = $type == 2 ? $return_fee : 0;
                unset($requestData['id'], $requestData['token']);
                $result = $change_model->save($requestData);
                $change_order_id = $change_model->id;
                //更改主订单数据
                if($result){
                    $update = ['change_status' => $change_status];
                    Order::where('id', $order['id'])->update($update);
                    Order::where('id', $order['id'])->inc('change_num', 1)->update();
                    if($type == 2 && $diff_money < 0){
                        //需退款 统计换车退款金额
                        Order::where('id', $order['id'])->inc('all_change_refund_money', abs($diff_money))->update();
                    }
                }
                Db::commit();
                $this->success('换车成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

    /**
     * 排车(换车)车辆列表
     */
    public function changeCarList(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $id = $requestData['id']??0;
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $order = Order::where(['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id])->find();
        if(!$id || !$order){
            $this->error('订单不存在');
        }
        $order = $order->toArray();
        $list = MerchantCar::field('id,car_id,merchant_car_name,car_number,car_price,drive,displacement')->with('carss')->where(['is_delete' => 1, 'status' => 1, 'examine_status' => 2, 'car_status' => 1, 'merchant_id' => $user['id']])->where('id', '<>', $order['merchant_car_id'])->order('createtime', 'desc')->page($page, $limit)->select()->toArray();
        if($list){
            foreach ($list as $key=>$value){
                $car_gear = MerchantCar::fetchCarGear($value['car_gear']);
                $value['car_label'] = $value['car_site'].'座|'.$value['car_gate'].'门|'.$car_gear . '|'. $value['displacement'];
                $value['car_price'] = floatval($value['car_price']);
                $list[$key] = $value;
            }
        }
        $this->success('请求成功', $list);
    }

    /**
     * 取车
     */
    public function pickCar(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $id = $requestData['id']??0;
        $validate = new \app\api\validate\Order();
        if (!$validate->scene('pick')->check($requestData)) {
            $this->error($validate->getError());
        }
        if(!isset($requestData['start_check_video']) && !isset($requestData['start_check_images'])){
            $this->error('取车验车视频和取车验车图必须至少上传一个');
        }
        if((isset($requestData['start_check_video']) && !$requestData['start_check_video']) && (isset($requestData['start_check_images']) && !$requestData['start_check_images'])){
            $this->error('取车验车视频和取车验车图必须至少上传一个');
        }
        $where = ['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id];
        $order = Order::where($where)->find();
        if(!$id || !$order){
            $this->error('订单不存在');
        }
        $order = $order->toArray();
        if($order['status'] != 1){
            $text = Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['continue_status'] == 2 || $order['continue_status'] == 3){
            $this->error('订单续租中');
        }
        if($order['face_status'] == 2){
            $this->error('订单当面付进行中');
        }
        Db::startTrans();
        try {
            $requestData['pick_time'] = time();
            $requestData['status'] = 2;
            unset($requestData['token'],$requestData['id']);
            $result = Order::where('id', $id)->update($requestData);
            Db::commit();
            $this->success('取车成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 还车
     */
    public function returnCar(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $id = $requestData['id']??0;
        $validate = new \app\api\validate\Order();
        if (!$validate->scene('return')->check($requestData)) {
            $this->error($validate->getError());
        }
        if((!isset($requestData['end_check_video'])) && !isset($requestData['start_check_images'])){
            $this->error('还车验车视频和取车验车图必须至少上传一个');
        }
        if(($requestData['end_check_video'] && !$requestData['end_check_video']) && (isset($requestData['end_check_images']) && !$requestData['end_check_images'])){
            $this->error('还车验车视频和取车验车图必须至少上传一个');
        }
        $where = ['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id];
        $order = Order::with(['orderChangePayed', 'orderContinuePayed'])->where($where)->find();
        if(!$id || !$order){
            $this->error('订单不存在');
        }
        $order = $order->toArray();
        if($order['status'] != 2){
            $text = Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['continue_status'] == 2 || $order['continue_status'] == 3){
            $this->error('订单续租中');
        }
        if($order['face_status'] == 2){
            $this->error('订单当面付进行中');
        }
//        dump($order);die;
        Db::startTrans();
        try {
            $requestData['return_time'] = time();
            $requestData['real_return_time'] = strtotime($requestData['real_return_time']);
            $requestData['status'] = 3;
            unset($requestData['token'],$requestData['id']);
            $result = Order::where('id', $id)->update($requestData);
            //车状态修改
            MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 1]);
            //计算商家分配比例余额
            $all_money = $order['all_money'];
            $all_refund_money = $order['refund_money'];
            if($order['orderChangePayed']){
                $all_money = $order['orderChangePayed'][0]['all_money'];
                $change_refund_money = array_column($order['orderChangePayed'], 'refund_money');
                $all_refund_money = bcadd($all_refund_money, array_sum($change_refund_money), 2);
            }
            if($order['orderContinuePayed']){
                $all_money_list = array_column($order['orderContinuePayed'], 'all_money');
                $continue_all_money = array_sum($all_money_list);
                $all_money = bcadd($all_money, $continue_all_money, 2);
                $continue_refund_money = array_column($order['orderContinuePayed'], 'refund_money');
                $all_refund_money = bcadd($all_refund_money, array_sum($continue_refund_money), 2);
            }
            $all_money = bcsub($all_money, $all_refund_money, 2);
            $rate_money = bcmul($all_money, $user['commission_rate']/100, 2);

            if($rate_money > 0){
                //商家余额增加
                Merchant::where('id', $user['id'])->inc('shop_balance', $rate_money)->update();
                $balance_log = [
                    'merchant_id' => $user['id'],
                    'amount' => $rate_money,
                    'type' => 1,
                    'log_note' => '预约订单确认还车获得',
                    'createtime' => time(),
                    'order_id' => $id,
                    'order_type' => 1,
                    'total_order_id' => $id
                ];
                BalanceLog::insert($balance_log);
                //上一级分销
                $distribution = \app\api\model\Config::where('name', 'distribution')->value('value');
                $order_user = User::where('id', $order['user_id'])->find();
                $parent_id = $order_user['parent_id']??0;
                if($distribution && $distribution > 0 && $parent_id){
                    $parent = User::where('id', $parent_id)->find();
                    $distribution_money = bcmul($all_money, $distribution/100, 2);
                    if($distribution_money > 0 && $parent){
                        User::where('id', $parent_id)->inc('money', $distribution_money)->update();
                        $new_money = bcadd($distribution_money, $parent['money'], 2);
                        $user_money_log = [
                            'user_id' => $parent_id,
                            'money' => $distribution_money,
                            'before' => $parent['money'],
                            'after' => $new_money,
                            'memo' => '订单分销收入',
                            'createtime' => time(),
                            'order_id' => $id,
                            'type' => 1,
                            'source_uid' => $order['user_id'],
                        ];
                        UserMoneyLog::insert($user_money_log);
                        //写入用户分销收入表
                        $user_income = [
                            'user_id' => $parent_id,
                            'source_uid' => $order['user_id'],
                            'amount' => $distribution_money,
                            'order_id' => $id,
                            'type' => 2,
                            'createtime' => time()
                        ];
                        UserIncome::insert($user_income);
                    }
                }
            }
            Db::commit();
            $this->success('还车成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 申请退款（已完成订单）
     */
    public function refundApply(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $id = $requestData['id']??0;
        $type = $requestData['type']??0;
        $money = $requestData['money']??0;
        $order_refund_type = $requestData['order_refund_type']??0;
        $order_refund_note = $requestData['order_refund_note']??0;
        $where = ['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id];
        $order = Order::with(['orderChangePayed', 'orderContinuePayed', 'orderFacePayed'])->where($where)->find();
        if(!$id || !$order || !$type || !in_array($type, [1,2])){
            $this->error('请求错误');
        }
        $order = $order->toArray();
        if($order['status'] != 3){
            $text = Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['continue_status'] == 2 || $order['continue_status'] == 3){
            $this->error('订单续租中');
        }
        if($order['face_status'] == 2){
            $this->error('订单当面付进行中');
        }
        if($order['order_refund_status'] == 2 || $order['order_refund_status'] == 3){
            $text = Order::fetchOrderRefundStatus($order['order_refund_status']);
            $this->error('订单退款' . $text);
        }
        if($type == 1){
            $type_list = RefundType::field('id,name')->where(['is_delete' => 1])->select();
            $data = [
                'order_id' => $id,
                'type_list' => $type_list
            ];
            $this->success('操作成功', $data);
        }else{
            if(!$money || !$order_refund_type){
                $this->error('请求错误');
            }
            $last_all_money = $order['last_all_money'];
            if($order['orderChangePayed']){
                $change_last_all_money = array_column($order['orderChangePayed'], 'last_all_money');
                $change_last_all_money = array_sum($change_last_all_money);
                $last_all_money = bcadd($last_all_money, $change_last_all_money, 2);
            }
            if($order['orderContinuePayed']){
                $continue_last_all_money = array_column($order['orderContinuePayed'], 'last_all_money');
                $continue_last_all_money = array_sum($continue_last_all_money);
                $last_all_money = bcadd($last_all_money, $continue_last_all_money, 2);
            }
            if($order['orderFacePayed']){
                $face_last_all_money = array_column($order['orderFacePayed'], 'last_all_money');
                $face_last_all_money = array_sum($face_last_all_money);
                $last_all_money = bcadd($last_all_money, $face_last_all_money, 2);
            }
            if($money > $last_all_money){
                $this->error('退款金额不能大于订单实际支付金额');
            }
            Db::startTrans();
            try {
                $res = Order::where('id', $id)->update(['order_refund_status' => 2, 'order_refund_money' => $money, 'order_refund_type' => $order_refund_type, 'order_refund_note' => $order_refund_note, 'order_refund_addtime' => time(), 'updatetime' => time()]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($res){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
        }
    }

    /**
     *  发起续租
     */
    public function continue(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $order_id = $requestData['order_id']??0;
        $type = $requestData['type']??0;
        $merchant_insure_id = $requestData['merchant_insure_id']??0;
        $end_time = $requestData['end_time']??'';
        if(!$order_id || !$type || !in_array($type, [1,2])){
            $this->error('参数错误');
        }
        if($type == 2 && (!$merchant_insure_id || !$end_time)){
            $this->error('参数错误');
        }
        $order = Order::where(['id' => $order_id, 'is_delete' => 1, 'merchant_id' => $user['id']])->whereIn('status', '1,2')->find();
        if(!$order){
            $this->error('订单不存在');
        }
        $order = $order->toArray();
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['continue_status'] == 2){
            $text = Order::fetchContinueStatus($order['continue_status']);
            $this->error('订单续租'.$text);
        }
        if($order['face_status'] == 2){
            $this->error('订单当面付款中');
        }
        $end_time = strtotime($end_time);
        $start_time = $order['end_time'];
        $continue_order = OrderContinue::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'pay_status' => 1])->whereIn('continue_status', '1,2')->count();
        if($continue_order){
            $this->error('用户有未完成的续租订单');
        }
        $merchant = Merchant::where(['is_delete' => 1, 'id' => $order['merchant_id']])->find();
        if(!$merchant){
            $this->error('商家不存在');
        }
        $merchant = $merchant->toArray();
        if($merchant['status'] == 2){
            $this->error('商家已下架');
        }
        $merchant_car = MerchantCar::where(['is_delete' => 1, 'id' => $order['merchant_car_id']])->find();
        if(!$merchant_car){
            $this->error('商家车辆不存在');
        }
        $merchant_car = $merchant_car->toArray();
        if($merchant['status'] == 2){
            $this->error('商家车辆已下架');
        }
        if($type == 1){
            if(!$merchant_insure_id){
                $merchant_insure_id = $order['insurance_id'];
            }
            //续租订单
            $last_continue_order = OrderContinue::where(['is_delete' => 1, 'order_id' => $order_id, 'user_id' => $order['user_id']])->where('pay_status', 'in', '2')->order('createtime', 'desc')->find();
            $start_time = $order['end_time'];
            if($last_continue_order){
                $start_time = $last_continue_order['end_time'];
            }
            if(!$end_time){
                $end_time = bcadd($start_time, 86400*2, 0);
            }
            $start_list = [
                'day' => date('m月d日', $start_time),
                'time' => date('H:i', $start_time),
                'week' => $this->week_list[date('w', $start_time)],
                'start_stamp' => $start_time,
                'year_day' => date('Y-m-d', $start_time)
            ];
            $end_list = [
                'day' => date('m月d日', $end_time),
                'time' => date('H:i', $end_time),
                'week' => $this->week_list[date('w', $end_time)],
                'end_stamp' => $end_time,
                'year_day' => date('Y-m-d', $end_time)
            ];
            //租车保障
            $insure_ids = Insure::where(['is_delete' => 1, 'status' => 1])->column('id');
            $insure_list = MerchantCarInsure::field('id,insure_id,price')->with('insures')->where(['is_delete' => 1, 'merchant_car_id' => $merchant_car['id'], 'id' => $order['insurance_id']])->where('insure_id', 'in', $insure_ids)->select()->toArray();
            foreach ($insure_list as $ke=>$vl){
                $vl['active'] = 0;
                if($merchant_insure_id && $merchant_insure_id == $vl['id']){
                    $vl['active'] = 1;
                }
                $vl['price'] = floatval($vl['price']);
                $insure_list[$ke] = $vl;
            }
            //保障规则和取消规则
            $config = \app\api\model\Config::where('name', 'in', 'car_guarantee,cancel_time1,cancel_money1,cancel_money2,platform_agreement')->column('value', 'name');
            //天数
            $days = ceil(bcdiv(bcsub($end_time, $start_time, 0), 86400, 2));
            //商家车辆远期价格
            $date_list = createDateRange(date('Y-m-d H:i', $start_time), date('Y-m-d H:i', $end_time));
            $merchant_car_price_list = MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $order['merchant_car_id']])->where('end_time', '>', time())->select()->toArray();
            $new_date_list = [];
            if($merchant_car_price_list){
                foreach ($date_list as $kk=>$vv){
                    $new_date['date'] = $vv;
                    $new_date['price'] = $merchant_car['car_price'];
                    foreach ($merchant_car_price_list as $kkk=>$vvv){
                        if(strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']){
                            if($days < $vvv['days']){
                                $this->error('起租天数必须大于' . $vvv['days']);
                            }
                            $new_date['price'] = $vvv['price'];
                        }else{
                            $new_date['price'] = $order['price'];
                        }
                    }
                    $new_date_list[] = $new_date;
                }
                $price_list = array_column($new_date_list, 'price');
                //租车费用
                $rental_money = array_sum($price_list);
            }else{
                $rental_money = bcmul($order['price'], $days, 2);
            }

            if($rental_money < 0.01){
                $this->error('租车费用必须大于0.01');
            }
            //判断取还车是否夜间
            $night_time = explode('-', $merchant['night_time']);
            $night_hour_list = getHours($night_time[0], $night_time[1]);
            $end_hour = date('H', $end_time);
            $night_return_fee = 0;
            if(in_array($end_hour, $night_hour_list)){
                $night_return_fee = $merchant_car['night_return_fee'];
            }
            //手续费
            $handle_fee = 0;
            //保险费用
            $merchant_insurance = MerchantCarInsure::where('id', $merchant_insure_id)->find();
            $insurance = $merchant_insurance['price']??0;
            $insurance_money = bcmul($insurance, $days, 2);
            //押金
            $car_deposit = 0;
            //总费用
            $all_money = bcadd($rental_money, ($insurance_money+$night_return_fee), 2);
            $merchant_car['car_price'] = floatval($merchant_car['car_price']);
            $merchant_car['car_deposit'] = floatval($merchant_car['car_deposit']);
            $result_order= [
                'id' => $order['id'],
                'out_trade_no' => $order['out_trade_no'],
                'price' => floatval($order['price']),
                'start_list' => $start_list,
                'end_list' => $end_list,
                'days' => $days,
                'merchant' => $merchant,
                'merchant_car' => $merchant_car,
                'rental_money' => floatval($rental_money),
                'handle_fee' => floatval($handle_fee),
                'car_deposit' => floatval($car_deposit),
                'insurance_money' => floatval($insurance_money),
                'all_money' => floatval($all_money),
                'insure_list' => $insure_list,
                'config' => $config,
                'night_return_fee' => floatval($night_return_fee)
            ];
            $this->success('请求成功', $result_order);
        }else{
            $start_date = date('Y-m-d', $start_time);
            $end_date = date('Y-m-d', $end_time);
            if($start_time >= $end_time){
                $this->error('结束时间不能大于开始时间');
            }
            $last_end_time = OrderContinue::where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order_id])->where('pay_status', 'in', '1,2,4')->order('createtime', 'desc')->value('end_time');
            if($last_end_time && $end_time < $last_end_time){
                $this->error('结束时间不能小于该订单最后一次续租时间');
            }
            //判断商家营业时间
            $open_time = explode('-', $merchant['open_time']);
            if($start_time < strtotime($start_date . ' ' . $open_time[0]) || $start_time > strtotime($start_date . ' ' . $open_time[1]) || $end_time < strtotime($end_date . ' ' . $open_time[0]) || $end_time > strtotime($end_date . ' ' . $open_time[1])){
                $this->error('商家营业时间：' . $open_time);
            }
            //临时下架时间
            $last_time = strtotime("-1 month");
            $merchant_car_time = MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $order['merchant_car_id']])->where('end_time', '>', $last_time)->select();
            foreach ($merchant_car_time as $ke=>$vl){
                $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], $start_time, $end_time);
                if($is_time_cross){
                    $this->error('租赁时间段内商家车辆会临时下架');
                }
            }
            //天数
            $days = ceil(bcdiv(bcsub($end_time, $start_time, 0), 86400, 2));
            //商家车辆远期价格
            $date_list = createDateRange(date('Y-m-d H:i', $order['start_time']), $requestData['end_time']);
            $merchant_car_price_list = MerchantCarPrice::field('start_time,end_time,price,days')->where(['is_delete' => 1, 'merchant_car_id' => $order['merchant_car_id']])->where('end_time', '>', time())->select()->toArray();
            $new_date_list = [];
            if($merchant_car_price_list){
                foreach ($date_list as $kk=>$vv){
                    $new_date['date'] = $vv;
                    $new_date['price'] = $merchant_car['car_price'];
                    foreach ($merchant_car_price_list as $kkk=>$vvv){
                        if(strtotime($vv) >= $vvv['start_time'] && strtotime($vv) <= $vvv['end_time']){
                            if($days < $vvv['days']){
                                $this->error('起租天数必须大于' . $vvv['days']);
                            }
                            $new_date['price'] = $vvv['price'];
                        }
                    }
                    $new_date_list[] = $new_date;
                }
                $price_list = array_column($new_date_list, 'price');
                $prices = implode(',', $price_list);
                //租车费用
                $rental_money = array_sum($price_list);
                //平均单价
                $car_price = bcdiv($rental_money, count($price_list), 2);
            }else{
                $rental_money = bcmul($order['price'], $days, 2);
                $car_price = $order['price'];
            }

            if($rental_money < 0.01){
                $this->error('租车费用必须大于0.01');
            }
            //判断取还车是否夜间
            $night_time = explode('-', $merchant['night_time']);
            $night_return_fee = 0;//夜间还车服务费用
            if($end_time >= strtotime($end_date . ' ' . $night_time[0]) && $end_time <= strtotime($end_date . ' ' . $night_time[1])){
                $night_return_fee = $merchant_car['night_return_fee'];
            }
            //手续费
            $handle_fee = 0;
            //保险费用
            $merchant_insurance = MerchantCarInsure::where('id', $merchant_insure_id)->find();
            $insurance = $merchant_insurance['price']??0;
            $insurance_money = bcmul($insurance, $days, 2);
            //押金
            $car_deposit = 0;
            //总费用
            $all_money = bcadd($rental_money, ($car_deposit+$insurance_money+$night_return_fee), 2);
            $change_order = [
                'user_id' => $order['user_id'],
                'order_id' => $order_id,
                'out_trade_no' => Order::getOutTradeNo('order_continue'),
                'merchant_car_id' => $order['merchant_car_id'],
                'merchant_id' => $order['merchant_id'],
                'start_time' => $start_time,
                'end_time' => $end_time,
                'days' => $days,
                'price' => $car_price,
                'rental_money' => $rental_money,
                'deposit' => $car_deposit,
                'all_money' => $all_money,
                'deposit_status' => $car_deposit > 0 ? 1 : 0,
                'send_type' => $order['send_type'],
                'createtime' => time(),
                'insurance' => $insurance_money,
                'insurance_id' => $merchant_insure_id,
                'pay_type' => $order['pay_type'],
                'handle_fee' => $handle_fee,
                'prices' => $prices,
                'continue_status' => 2,
                'last_all_money' => $all_money,
                'night_return_fee' => $night_return_fee
            ];
            Db::startTrans();
            try {
                OrderContinue::insert($change_order);
                Order::where('id',  $order['id'])->update(['continue_status' => 3]);
                Order::where('id', $order['id'])->inc('continue_num', 1)->update();
                Db::commit();
                $this->success('请求成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

    /**
     * 续租审核
     */
    public function continueStatus(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $id = $requestData['id']??0;
        $status = $requestData['status']??0;
        if(!$id || !$status || !in_array($status, [1,2])){
            $this->error('参数错误');
        }
        $where = ['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id, 'pay_status' => 1, 'continue_status' => 1];
        $order_continue = OrderContinue::where($where)->find();
        if(!$order_continue){
            $this->error('续租订单不存在');
        }
        $order_continue = $order_continue->toArray();
        $order = Order::where(['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $order_continue['order_id']])->find();
        if(!$order){
            $this->error('主订单不存在');
        }
        if($order['status'] != 2 && $order['status'] != 1){
            $text = Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['continue_status'] != 2){
            $this->error('订单续租未在申请中');
        }
        if($order['face_status'] == 2){
            $this->error('订单当面付进行中');
        }
        Db::startTrans();
        try {
            $update = [
                'continue_status' => $status == 1 ? 2 : 3,
                'exmain_time' => time()
            ];
            $result = OrderContinue::where('id', $id)->update($update);
            //主订单
            $order_update = [
                'continue_status' => $status == 1 ? 3 : 5,
            ];
            Order::where('id', $order['id'])->update($order_update);
            if($status == 2){
                Order::where('id', $order['id'])->dec('continue_num', 1)->update();
            }
            Db::commit();
            $this->success('审核成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     *  续租订单详情
     */
    public function continueDetail(){
        $requestData = $this->request->post();
        $user = $this->auth->getUser();
        $id = $requestData['id']??0;
        $continue_order = OrderContinue::field('id,order_id,merchant_id,merchant_car_id,out_trade_no,start_time,end_time,days,price,rental_money,deposit,all_money,pay_status,deposit_status,insurance_id,insurance,insurance_price,handle_fee,continue_status,createtime')->where(['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id])->find();
        if(!$continue_order){
            $this->error('续租订单不存在');
        }
        $merchant_car = MerchantCar::with('carss')->where('id', $continue_order['merchant_car_id'])->find();
        $car_gear = MerchantCar::fetchCarGear($merchant_car['car_gear']);
        $continue_order['car_sign'] = $merchant_car['car_site'].'座|'.$merchant_car['car_gate'].'门|'.$car_gear.'|'.$merchant_car['displacement'];
        $continue_order['merchant_car_name'] = $merchant_car['merchant_car_name'];
        $continue_order['car_number'] = $merchant_car['car_number'];
        $continue_order['car_name'] = $merchant_car['car_name'];
        $continue_order['car_image'] = $merchant_car['car_image'];
        $res = getDhir($continue_order['start_time'], $continue_order['end_time']);
        if($res['d'] > 0){
            $days_new = $res['h'] > 0 ? $res['d'] . '天' . $res['h'] . '小时' : $res['d'] . '小时';
        }else{
            $days_new = $res['h'] . '小时';
        }
        $continue_order['days_new'] = $days_new;
        $merchant_insure = MerchantCarInsure::where('id', $continue_order['insurance_id'])->find();
        $continue_order['insure_name'] = $merchant_insure['insure_name'];
        $continue_order['createtime'] = date('Y-m-d H:i:s', $continue_order['createtime']);
        $start_time = [
            'day' => date('m月d日', $continue_order['start_time']),
            'time' => date('H:i', $continue_order['start_time']),
            'week' => $this->week_list[date('w', $continue_order['start_time'])]
        ];
        $continue_order['start_time_list'] = $start_time;
        $end_time = [
            'day' => date('m月d日', $continue_order['end_time']),
            'time' => date('H:i', $continue_order['end_time']),
            'week' => $this->week_list[date('w', $continue_order['end_time'])]
        ];
        $continue_order['end_time_list'] = $end_time;
        $continue_order['price'] = floatval($continue_order['price']);
        $continue_order['rental_money'] = floatval($continue_order['rental_money']);
        $continue_order['all_money'] = floatval($continue_order['all_money']);
        $continue_order['insurance'] = floatval($continue_order['insurance']);
        $continue_order['insurance_price'] = floatval($continue_order['insurance_price']);
        $continue_order['handle_fee'] = floatval($continue_order['handle_fee']);
        $this->success('请求成功', $continue_order);
    }

    /**
     *  当面收费订单详情
     */
    public function faceDetail(){
        $requestData = $this->request->post();
        $user = $this->auth->getUser();
        $id = $requestData['id']??0;
        $face_order = OrderFace::field('id,order_id,out_trade_no,all_money,status,type,createtime,content,time_end')->where(['is_delete' => 1, 'merchant_id' => $user['id'], 'id' => $id])->find();
        if(!$face_order){
            $this->error('当面收费订单不存在');
        }
        $type = FaceCate::where('id', $face_order['type'])->find();
        $face_order['type_name'] = $type['name']??'';
        $face_order['createtime'] = date('Y-m-d H:i:s', $face_order['createtime']);
        $face_order['time_end'] = $face_order['time_end'] ? date('Y-m-d H:i:s', $face_order['time_end']) : '';
        $face_order['all_money'] = floatval($face_order['all_money']);
        $this->success('请求成功', $face_order);
    }

    /**
     *  当面付创建收费
     */
    public function orderFace(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $type = $requestData['type']??0;
        $order_id = $requestData['order_id']??0;
        $cate_id = $requestData['cate_id']??0;
        $all_money = $requestData['all_money']??0;
        $content = $requestData['content']??'';
        if(!$order_id || !$type || !in_array($type, [1,2])){
            $this->error('参数错误');
        }
        $order = Order::where(['id' => $order_id, 'is_delete' => 1, 'merchant_id' => $user['id']])->whereIn('status', '1,2,3')->find();
        if(!$order){
            $this->error('订单不存在');
        }
        $order = $order->toArray();
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['continue_status'] == 2 || $order['continue_status'] == 3){
            $this->error('订单续租中');
        }
        if($order['face_status'] == 2){
            $this->error('订单当面付款中');
        }
        if($order['order_refund_status'] == 2){
            $text = Order::fetchOrderRefundStatus($order['order_refund_status']);
            $this->error('订单退款' . $text);
        }

        if($type == 1){//查看
            $list = FaceCate::field('id,name')->where(['is_delete' => 1])->order('createtime', 'desc')->select()->toArray();
            $this->success('请求成功', $list);
        }else{
            if(!$cate_id || !$all_money || $all_money < 0.01){
                $this->error('参数错误');
            }
            $cate = FaceCate::where(['is_delete' => 1, 'id' => $cate_id])->find();
            if(!$cate){
                $this->error('付款类型不存在');
            }
            $face_order = [
                'user_id' => $order['user_id'],
                'order_id' => $order_id,
                'merchant_id' => $order['merchant_id'],
                'out_trade_no' => Order::getOutTradeNo('order_face'),
                'all_money' => $all_money,
                'type' => $cate_id,
                'createtime' => time(),
                'content' => $content,
                'pay_type' => $order['pay_type'],
            ];
            Db::startTrans();
            try {
                OrderFace::insert($face_order);
                Order::where('id',  $order['id'])->update(['face_status' => 2]);
                Order::where('id', $order['id'])->inc('face_num', 1)->update();
                Db::commit();
                $this->success('请求成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

    }

    /**
     *  换车总退款申请审核
     */
    public function changeRefund(){
        $user = $this->auth->getUser();
        $requestData = $this->request->post();
        $order_id = $requestData['order_id']??0;
        if(!$order_id){
            $this->error('请求错误');
        }
        $order = Order::where(['merchant_id' => $user['id'], 'is_delete' => 1, 'id' => $order_id])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['status'] != 3){
            $text = Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if($order['continue_status'] == 2 || $order['continue_status'] == 3){
            $this->error('订单续租中');
        }
        if($order['change_status'] == 2){
            $this->error('订单换车中');
        }
        if($order['face_status'] == 2){
            $this->error('订单当面付中');
        }
        if($order['refund_status'] == 2 || $order['refund_status'] == 3){
            $text = Order::fetchRefundStatus($order['refund_status']);
            $this->error('订单换车退款'.$text);
        }
        if($order['all_change_refund_money'] == 0){
            $this->error('订单换车应退金额为0');
        }
        $refund_order = [
            'user_id' => $user['id'],
            'merchant_id' => $order['merchant_id'],
            'order_id' => $order['id'],
            'out_refund_no' => Order::getOutRefundNo('order_refund'),
            'all_money' => $order['all_change_refund_money'],
            'createtime' => time(),
        ];
        Db::startTrans();
        try {
            $result = OrderRefund::insert($refund_order);
            Order::where('id', $order_id)->update(['refund_status' => 2]);
            //向商家发送短信
            $merchant_phone = \app\api\model\Merchant::where(['is_delete' => 1, 'id' => $order['merchant_id']])->value('merchant_phone');
            if($merchant_phone){
                $data = [
                    'number' => $order['out_trade_no'],
                    'money' => $order['all_change_refund_money'],
                ];
                $res = sendMsg($merchant_phone, $data, 'SMS_464071177');
            }
            //向用户发送短信
            $data = [
                'number' => $order['out_trade_no'],
                'money' => $order['all_change_refund_money'],
            ];
            $res = sendMsg($order['user_phone'], $data, 'SMS_464056170');
            Db::commit();
            if($result){
                $this->success('请求成功');
            }else{
                $this->error('请求失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     *  我的钱包
     */
    public function mywallet(){
        $user = $this->auth->getUser();
        $params = $this->request->post();
        $balance = floatval($user['shop_balance']);
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        //提现列表
        $cashList = Cash::field('id,amount,createtime,status')->where(['merchant_id' =>  $user['id']])->page($page,$limit)->select()->toArray();
//        if (!empty($cashList)){
            foreach ($cashList as $key=>$val){
                $cashList[$key]['createtime'] = date('Y-m-d H:i:s');
                $cashList[$key]['amount'] = $val['amount'];
            }
            $newData = [
                'cashlist' => $cashList,
                'balance' => $balance
            ];
            $this->success('获取成功',$newData);
//        }else{
//            $this->error('暂无数据');
//        }

    }

    /**
     *  提现页面查看与提现
     */
    public function cash(){
        $user = $this->auth->getUser();
        $params = $this->request->post();
        if (!isset($params['see'])){
            $this->error('参数错误');
        }
        if ($params['see'] == 1){
            $info = [
                'balance' => floatval($user['shop_balance']),
                'name' => $user['merchant_name'],
                'account' => $user['alipay_account'],
                'alipay_name' => $user['alipay_name']
            ];
            $this->success('获取成功',$info);
        }else{
            if(!$user['alipay_name'] || !$user['alipay_account']){
                $this->error('请完善支付宝账户信息');
            }
            if (!isset($params['money'])){
                $this->error('参数错误');
            }
            if (!$params['money'] || $params['money'] < 0.1){
                $this->error('提现金额不能小于0.1');
            }
            if ($params['money'] > $user['shop_balance']){
                $this->error('提现金额不能大于余额');
            }
            $merchant_cash_rate = \app\api\model\Config::where('name', 'merchant_cash_rate')->value('value');
            $fee = 0;
            if($merchant_cash_rate){
                $fee = bcmul($params['money'], $merchant_cash_rate/100, 2);
            }
            //提现数据重组
            $time = time();
            $data = [
                'out_trade_no' => sys_create_orderno(2),
                'merchant_id'  => $user['id'],
                'amount'  => $params['money'],
                'fee' => $fee,
                'cash_amount' => bcsub($params['money'], $fee, 2),
                'status'  => 1,
                'createtime'  => $time,
                'truename'  => $user['alipay_name'],
                'alipay_account'  => $user['alipay_account'],
            ];
            $model = new Cash();
            $result = $model->allowField([])->save($data);
            //更新店铺余额
            Merchant::where(['id' => $user['id']])->dec('shop_balance',$params['money'])->update();
            BalanceLog::insert(['merchant_id' => $user['id'],'amount' => $params['money'],'type' => 2,'createtime' => $time,'order_id' => $model->id,'order_type' => 2]);
            if ($result){
                $this->success('申请成功');
            }else{
                $this->error('申请失败');
            }
        }
    }

    /**
     *  取消预约
     */
    public function orderRefund($requestData, $user){
        $order_id = $requestData['order_id']??0;
        $money = $requestData['money']??'';
        if(!$order_id || !$money){
            return ['status' => 0, 'message' => '参数错误', 'result' => ''];
        }
        $order = Order::with(['order_change_payed', 'order_continue_payed', 'order_face_payed'])->where(['id' => $order_id, 'user_id' => $user['id'], 'is_delete' => 1, 'status' => 1])->find()->toArray();
        if(!$order){
            return ['status' => 0, 'message' => '订单不存在', 'result' => ''];
        }
        Db::startTrans();
        try {

            Db::commit();
            return ['status' => 1, 'message' => '请求成功', 'result' => ''];
        } catch (Exception $e) {
            Db::rollback();
            return ['status' => 0, 'message' => $e->getMessage(), 'result' => ''];
        }
    }

     //微信退款
    public function wechatRefund($order, $user, $type = 1){
            $refundFee = $type == 1 ? $order['refund_money']*100 : $order['deposit']*100;
            $refundDesc = $type == 1 ? '取消订单退款' : ($type == 2 ? '押金退款' : '换车退款');
            $config = Config::get('config_wechat.wechat_pay');
            $app = Factory::payment($config);
            $result = $app->refund->byOutTradeNumber($order['out_trade_no'], $order['out_refund_no'], $order['all_money']*100, $refundFee, [
                // 可在此处传入其他参数，详细参数见微信支付文档
                'refund_desc' => $refundDesc,
            ]);
            return $result;
        }

    //支付宝退款
    public function alipayRefund($order, $user, $type = 1){
            $refundFee = $type == 1 ? $order['refund_money'] : $order['deposit'];
            alipayFactory::setOptions(getOption());
            $result = alipayFactory::payment()->common()->refund($order['out_trade_no'], $refundFee);
            if(!$result){
                return false;
            }
            if($result->code != 10000){
                return false;
                $result->msg."，".$result->sub_msg.PHP_EOL;
            }
            $return_result = json_decode($result->httpBody, true);
            return $return_result['alipay_trade_refund_response'];
        }

}
